package com.syyo.admin.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.syyo.admin.common.listener.UploadDataListener;
import com.syyo.admin.domain.entity.DeptEntity;
import com.syyo.admin.domain.entity.UserEntity;
import com.syyo.admin.domain.export.UserExport;
import com.syyo.admin.domain.export.UserImport;
import com.syyo.admin.domain.req.UserReq;
import com.syyo.admin.domain.resp.DeptResp;
import com.syyo.admin.domain.resp.UserResp;
import com.syyo.admin.mapper.DeptMapper;
import com.syyo.admin.mapper.UserMapper;
import com.syyo.admin.mapper.UserRoleMapper;
import com.syyo.admin.service.UserService;
import com.syyo.common.constant.SettingsConstant;
import com.syyo.common.enums.ResultEnum;
import com.syyo.common.exception.SysException;
import com.syyo.common.utils.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wang
 * @since 2020-07-17
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private SettingsConstant settingsConstant;

    @Autowired
    private DeptMapper deptMapper;

    @Override
    @Transactional
    public int add(UserReq req, Integer deptId) {
        UserEntity entity = new UserEntity();
        BeanUtils.copyProperties(req,entity);
        entity.setStatus(1);//默认状态为可用
        entity.setDeptId(deptId);
        String encode = passwordEncoder.encode(req.getPassWord());
        entity.setPassWord(encode);
        LocalDateTime now = LocalDateTime.now();
        entity.setCreateTime(now);
        entity.setUpdateTime(now);
        //添加用户
        int insert = userMapper.insert(entity);
        if (insert != 1) {
            throw new SysException(ResultEnum.E_80001.getCode(), ResultEnum.E_80001.getMessage());
        }

        //添加角色菜单中间表
        List<Integer> roleIdList = req.getRoleIdList();
        if (MyListUtils.isNotEmpty(roleIdList)) {
            // 只有admin用户才能设置admin角色
            if (roleIdList.contains(1)) {
                if (!"admin".equals(SecurityUtils.getUsername())) {
                    throw new SysException(ResultEnum.E_90008.getCode(), ResultEnum.E_90008.getMessage());
                }
            }
            Integer userId = entity.getUserId();
            Integer add = userRoleMapper.addAll(userId, roleIdList);
            if (add != roleIdList.size()) {
                throw new SysException(ResultEnum.E_80011.getCode(), ResultEnum.E_80011.getMessage());
            }
        }
        return insert;

    }

    @Override
    @Transactional
    public int del(UserReq  req, Integer deptId) {
        List<Integer> ids = req.getIds();
        // admin用户不能删除
        if (ids.contains(1)) {
            throw new SysException(ResultEnum.E_90007.getCode(), ResultEnum.E_90007.getMessage());
        }
        // 批量删除
        boolean b = removeByIds(ids);
        if (!b) {
            throw new SysException(ResultEnum.E_80002.getCode(), ResultEnum.E_80002.getMessage());
        }
        // 删除关联的用户角色表
        for (Integer id : ids) {
            userRoleMapper.del(id);
        }
        return 1;
    }

    @Override
    @Transactional
    public int edit(UserReq req, Integer deptId) {
        UserEntity entity = new UserEntity();
        BeanUtils.copyProperties(req,entity);
        entity.setDeptId(deptId);
        LocalDateTime now = LocalDateTime.now();
        entity.setUpdateTime(now);
        int insert = userMapper.updateById(entity);
        if (insert != 1) {
            throw new SysException(ResultEnum.E_80003.getCode(), ResultEnum.E_80003.getMessage());
        }

        //添加角色菜单中间表
        List<Integer> roleIdList = req.getRoleIdList();
        if (MyListUtils.isNotEmpty(roleIdList)) {
            // 只有admin用户才能设置admin角色
            if (roleIdList.contains(1)) {
                String username = SecurityUtils.getUsername();
                if (!"admin".equals(SecurityUtils.getUsername())) {
                    throw new SysException(ResultEnum.E_90008.getCode(), ResultEnum.E_90008.getMessage());
                }
            }
            Integer userId = entity.getUserId();
            //删除之前用户角色中间表的数据
            Integer del = userRoleMapper.del(userId);

            //添加用户角色中间表
            Integer add = userRoleMapper.addAll(userId, roleIdList);
            if (add != roleIdList.size()) {
                throw new SysException(ResultEnum.E_80011.getCode(), ResultEnum.E_80011.getMessage());
            }
        }
        return insert;
    }

    @Override
    public UserResp findOne(Integer id) {
        UserEntity entity = userMapper.selectById(id);
        // 关联角色id
        List<Integer> list = userRoleMapper.findRole(id);
        UserResp userResp = new UserResp();
        BeanUtils.copyProperties(entity,userResp);
        userResp.setRoleIdList(list);
        // 查询用户关联的部门
        DeptResp dept = deptMapper.getDeptByUserId(id);
        userResp.setDeptName(dept.getDeptName());
        return userResp;
    }

    @Override
    public Map<String, Object> findAll(Integer pageNum, Integer pageSize, UserReq req, Integer deptId) {
        List<Integer> deptIds = new ArrayList<>();
        List<Integer> children = deptMapper.getChildren(deptId);
        deptIds.add(deptId);
        if (MyListUtils.isNotEmpty(children)){
            deptIds.addAll(children);
        }
        Page<UserEntity> teacherPage = new Page<UserEntity>(pageNum, pageSize);
        QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
        //判断条件值是否为空，如果不为空拼接条件
        if (MyStringUtils.isNotEmpty(req.getUserName())) {
            //构建条件
            wrapper.like("user_name", req.getUserName());
        }

        if (MyStringUtils.isNotEmpty(req.getStartDate())) {
            //构建条件
            wrapper.between("create_time", req.getStartDate(),req.getEndDate());
        }

        wrapper.in("dept_id", deptIds);
        IPage<UserEntity> list = userMapper.selectPage(teacherPage, wrapper);
        List<UserResp> userResps = new ArrayList<>();
        for (UserEntity user : list.getRecords()) {
            DeptResp dept = deptMapper.getDeptByUserId(user.getUserId());
            UserResp userResp = new UserResp();
            BeanUtils.copyProperties(user,userResp);
            userResp.setDeptName(dept.getDeptName());
            userResps.add(userResp);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("current", list.getCurrent());
        map.put("pages", list.getPages());
        map.put("records", userResps);
        map.put("size", list.getSize());
        map.put("total", list.getTotal());
        return map;
    }

    @Override
    @Transactional
    public Map<String, Object> importUser(MultipartFile file) throws IOException {
        // 读取到的文件
        List<UserImport> importEmps = EasyExcel.read(file.getInputStream(), UserImport.class, new UploadDataListener(userMapper)).sheet().doReadSync();
        //  导入数据库
        int count = importEmps.size();
        int countok = importEmps.size();
        Map<String, Object> map = new HashMap<>();
        map.put("count", count);
        map.put("countOk", countok);
        return map;
    }

    @Override
    public void exportUser(UserExport userExport, HttpServletResponse response) {
        List<UserEntity> sysUsers = userMapper.selectList(null);
        List<UserExport> list = new ArrayList<>();
        for (UserEntity sysUser : sysUsers) {
            UserExport userExport1 = new UserExport();
            userExport1.setUserName(sysUser.getUserName());
            userExport1.setNickName(sysUser.getNickName());
            userExport1.setEmail(sysUser.getEmail());
            userExport1.setPhone(sysUser.getPhone());
            list.add(userExport1);
        }
        // 导出文件
        MyFileUtil.exportFile(response,"user_",list, UserExport.class);
    }

    @Override
    @Transactional
    public int editPwd(UserReq req) {
        // 获取用户名
        UserEntity sysUser = getUserByName();
        String oldPwdRsa = req.getPassWord();
        String newPwdRsa = req.getNewPassWord();
        // RSA 解密
        String oldPwd = MyRsaUtils.decrypt(oldPwdRsa, settingsConstant.getPrivateKey());
        String newPwd = MyRsaUtils.decrypt(newPwdRsa, settingsConstant.getPrivateKey());

        if (!passwordEncoder.matches(oldPwd, sysUser.getPassWord())) {
            throw new SysException(ResultEnum.E_80008.getCode(), ResultEnum.E_80008.getMessage());
        }
        if (passwordEncoder.matches(newPwd, sysUser.getPassWord())) {
            throw new SysException(ResultEnum.E_80009.getCode(), ResultEnum.E_80009.getMessage());
        }
        UserEntity newsysUser = new UserEntity();
        newsysUser.setUserId(sysUser.getUserId());
        newsysUser.setPassWord(passwordEncoder.encode(newPwd));
        int insert = userMapper.updateById(newsysUser);
        if (insert != 1) {
            throw new SysException(ResultEnum.E_80003.getCode(), ResultEnum.E_80003.getMessage());
        }
        return insert;
    }

    private UserEntity getUserByName() {
        String username = SecurityUtils.getUsername();
        QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name", username);
        UserEntity sysUser = userMapper.selectOne(wrapper);
        if (sysUser == null) {
            throw new SysException(ResultEnum.E_80005.getCode(), ResultEnum.E_80005.getMessage());
        }
        return sysUser;
    }

    @Override
    @Transactional
    public int editAvatar(MultipartFile multipartFile) {
        // 获取用户名
        UserEntity sysUser = getUserByName();
        File file = MyFileUtil.upload(multipartFile, settingsConstant.getImagePath());
        assert file != null;
        UserEntity newsysUser = new UserEntity();
        newsysUser.setUserId(sysUser.getUserId());
        newsysUser.setAvatar(file.getPath());
        int insert = userMapper.updateById(newsysUser);
        if (insert != 1) {
            throw new SysException(ResultEnum.E_80003.getCode(), ResultEnum.E_80003.getMessage());
        }
        return insert;
    }

    @Override
    @Transactional
    public int editStatus(UserReq req) {
        UserEntity sysUser = new UserEntity();
        sysUser.setUserId(req.getUserId());
        sysUser.setStatus(req.getStatus());
        LocalDateTime now = LocalDateTime.now();
        sysUser.setUpdateTime(now);
        int insert = userMapper.updateById(sysUser);
        if (insert != 1) {
            throw new SysException(ResultEnum.E_80003.getCode(), ResultEnum.E_80003.getMessage());
        }
        return insert;
    }

    @Override
    public Map<String, Object> findUserAndDept(Integer deptId) {
        // 查询组织架构
        if (deptId == null) {
            deptId = 0;
        }
        List<DeptEntity> pDept = deptMapper.selectList((new QueryWrapper<DeptEntity>().eq("pid", deptId)));

        List<Map<String, String>> deptList = pDept.stream().map(item -> {
            Map<String, String> deptMap = new HashMap<>();
            deptMap.put("id", item.getDeptId() + "");
            deptMap.put("deptName", item.getDeptName());
            deptMap.put("pid", item.getPid() + "");
            return deptMap;
        }).collect(Collectors.toList());

        // 查询当前部门下的员工
        List<UserEntity> users = userMapper.selectList((new QueryWrapper<UserEntity>().eq("dept_id", deptId)));
        List<Map<String, String>> userList = users.stream().map(item -> {
            Map<String, String> userMap = new HashMap<>();
            userMap.put("id", item.getUserId() + "");
            userMap.put("userName", item.getUserName());
            return userMap;
        }).collect(Collectors.toList());

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("deptList", deptList);
        resultMap.put("userList", userList);
        return resultMap;
    }
}
